// 购物车
<template>
  <div class="cart-view">
    <h2>我的购物车</h2>

    <div v-if="cartItems.length === 0" class="empty-cart">
      <p>您的购物车是空的</p>
      <router-link to="/products" class="btn btn-primary">
        去选购商品
      </router-link>
    </div>

    <div v-else>
      <div class="cart-items">
        <div v-for="item in cartItems" :key="item.id" class="cart-item mb-3 p-3 border rounded">
          <div class="d-flex align-items-center">
            <img
                :src="item.product.imageUrl || 'https://via.placeholder.com/80'"
                class="me-3"
                width="80"
                alt="商品图片"
            >
            <div class="flex-grow-1">
              <h5>{{ item.product.name }}</h5>
              <p class="text-danger fw-bold">¥{{ item.product.price }}</p>
            </div>
            <div class="quantity-control">
              <button
                  class="btn btn-sm btn-outline-secondary"
                  @click="updateQuantity(item.id, item.quantity - 1)"
                  :disabled="item.quantity <= 1"
              >
                -
              </button>
              <span class="mx-2">{{ item.quantity }}</span>
              <button
                  class="btn btn-sm btn-outline-secondary"
                  @click="updateQuantity(item.id, item.quantity + 1)"
              >
                +
              </button>
            </div>
            <div class="ms-3">
              <button
                  class="btn btn-danger btn-sm"
                  @click="removeItem(item.id)"
              >
                <i class="bi bi-trash"></i>
              </button>
            </div>
          </div>
        </div>
      </div>

      <div class="cart-summary border-top pt-3 mt-3">
        <div class="d-flex justify-content-between">
          <h4>总计:</h4>
          <h4 class="text-danger">¥{{ totalAmount }}</h4>
        </div>
        <button
            class="btn btn-success w-100 mt-3"
            @click="checkout"
        >
          结算下单
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { cartApi } from '@/api'

export default {
  setup() {
    const router = useRouter()
    const cartItems = ref([])
    const userId = localStorage.getItem('userId')

    const totalAmount = computed(() => {
      return cartItems.value.reduce((sum, item) => {
        return sum + (item.product.price * item.quantity)
      }, 0).toFixed(2)
    })

    const loadCart = async () => {
      if (!userId) {
        router.push('/login')
        return
      }

      try {
        cartItems.value = await cartApi.getCart()
      } catch (error) {
        console.error('加载购物车失败:', error)
      }
    }

    const updateQuantity = async (itemId, newQuantity) => {
      if (newQuantity < 1) return

      try {
        await cartApi.updateItem(itemId, newQuantity)
        loadCart()
      } catch (error) {
        console.error('更新数量失败:', error)
      }
    }

    const removeItem = async (itemId) => {
      try {
        await cartApi.removeItem(itemId)
        loadCart()
      } catch (error) {
        console.error('移除商品失败:', error)
      }
    }

    const checkout = () => {
      router.push('/orders/create')
    }

    onMounted(loadCart)

    return {
      cartItems,
      totalAmount,
      updateQuantity,
      removeItem,
      checkout
    }
  }
}
</script>

<style scoped>
.empty-cart {
  text-align: center;
  padding: 50px 0;
}

.quantity-control {
  min-width: 120px;
}

.cart-item {
  background-color: #f8f9fa;
}
</style>